#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include <glib.h>

#include "kylin-verify.h"


/*
 * key_file_get_value, get value from key_file with group and key
 */
char* key_file_get_value(GKeyFile* key_file, char* group, char* key)
{
	gboolean res;
	GError* error;

	res = g_key_file_has_group (key_file, group);
	if(!res)
	{
		//printf("Key file does not have group '%s'.\n", group);
		return NULL;
	}

	res = g_key_file_has_key (key_file, group, key, &error);
	if(!res)
	{
		//printf("Key file does not have key '%s' under group '%s'.\n",key, group);
		return NULL;
	}

	return g_key_file_get_value (key_file, group, key, &error);
}

/*
 * key_file_set_value, set value to key_file with group and key
 */
void key_file_set_value (GKeyFile* key_file, const char* group, const char* key, const char* value)
{
	g_key_file_set_value (key_file, group, key, value);
}

/*
 * key_file_to_data, get plain text of a key file
 */
char* key_file_to_data (GKeyFile* key_file, gsize* size)
{
	return g_key_file_to_data(key_file, size, NULL);
}

/*
 * key_file_load_from_file, load key file from file name
 */
GKeyFile* key_file_load_from_file(const char* file_name)
{
	GKeyFile* key_file;
	GKeyFileFlags flags;
	GError *error = NULL;
	gboolean res;

	key_file = g_key_file_new();
	flags = G_KEY_FILE_KEEP_COMMENTS | G_KEY_FILE_KEEP_TRANSLATIONS;

	res = g_key_file_load_from_file (key_file, file_name, flags, &error);
	if(!res)
		goto out;

	return key_file;

out:
	if(key_file) {
		g_key_file_free(key_file);
		key_file = NULL;
	}

	if(error) {
		g_error_free(error);
		error = NULL;
	}
	return NULL;
}

/*
 * key_file_save_to_file, save key file content to file
 */
void key_file_save_to_file(GKeyFile* key_file, const char* file_name)
{
	GError *local_error = NULL;
	char *contents;
	gsize length;

	contents = g_key_file_to_data (key_file, &length, &local_error);

	if (local_error != NULL)
	{
		g_warning ("Unable to save settings: %s", local_error->message);
		g_error_free (local_error);
		return;
	}
	
	local_error = NULL;
	g_file_set_contents (file_name,
			     contents,
			     length,
			     &local_error);
	if (local_error != NULL)
	{
		g_warning ("Unable to save settings: %s", local_error->message);
		g_error_free (local_error);
		g_free (contents);
		return;
	}

	g_free (contents);
}
